package datastructure;

/**
 * @Author leecho
 * @Date: 2021/10/21 13:30
 * @Version 1.0
 */

public class HashTableDemo {
    public static void main(String[] args) {
        HashTable hashTable = new HashTable(10);

        hashTable.addEmp(new Employee(1,"AA"));
        hashTable.addEmp(new Employee(2,"BB"));
        hashTable.addEmp(new Employee(3,"CC"));

        hashTable.listHashTable();
    }
}

class HashTable{
    /*
    * 思路
    * - 创建一个链表数组来定位每一条链表
    * - 添加节点的时候，可以通过添加节点的no取模来定位到具体的某一条链表
    *    - 链表中的添加节点和前面实现的链表添加方法类似，这里不做过多赘述
    * */
    private int size;

    private EmpLinkList[] empLinkLists;

    public HashTable(int size) {
        this.size = size;
        empLinkLists = new EmpLinkList[size];
        for (int i = 0; i < empLinkLists.length; i++) {
            empLinkLists[i] = new EmpLinkList();
        }
    }

    public void addEmp(Employee emp){
        int no = empNo(emp);
        empLinkLists[no].addEmp(emp);
    }

    public int empNo(Employee emp){
        return emp.getId() % size;
    }

    public void listHashTable(){
        for (int i = 0; i < empLinkLists.length; i++) {
            empLinkLists[i].listEmpLinkList(i);
        }
    }
}

class EmpLinkList{
    private Employee head = null;

    public void addEmp(Employee emp){
        if (head== null){
            head = emp;
            return;
        }

        Employee tempEmp = head;
        while (true){
            if (tempEmp.getNext() == null){
                break;
            }
            tempEmp = tempEmp.getNext();
        }
        tempEmp.setNext(emp);
    }

    public void listEmpLinkList(int no){
        if (head == null)
            return;
        System.out.println("这是第"+no+"链表：");

        Employee tempEmp = head;
        while (true){
            System.out.println(tempEmp.getId() +"   "+tempEmp.getName());
            if (tempEmp.getNext() == null){
                break;
            }
            tempEmp = tempEmp.getNext();
        }
    }

}

class Employee{
    private Employee next;
    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Employee getNext() {
        return next;
    }

    public void setNext(Employee next) {
        this.next = next;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
